<template>
  <!-- 弹窗对话框，根据mode的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    :confirmBtn="EDIT_FORM_SAVE_BUTTON(mode)"
    @cancel="handleClose"
    @close="handleClose"
    size="85%"
  >
    <FormInfo>
      <template #left>供应编号：{{ meta.providerNo }}</template>
      <template #content>
        <t-form :disabled="pageData.readOnly">
          <t-space direction="vertical" style="width: 100%">
            <t-row>
              <t-col :span="3">
                <t-form-item label="状态">
                  <t-switch v-model="pageData.newStatus" :customValue="[0, 1]">
                    <template #label="slotProps">{{ slotProps.value ? "禁用" : "启用" }}</template>
                  </t-switch>
                </t-form-item>
              </t-col>
            </t-row>
            <t-row>
              <t-col :span="3">
                <t-form-item label="创建人">
                  <div class="form__text">{{ meta.createdByName }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="创建日期">
                  <div class="form__text">{{ dayjs(meta.createdTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="更新人" v-if="meta.updatedTime !== null">
                  <div class="form__text">{{ meta.updatedByName }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="更新日期" v-if="meta.updatedTime !== null">
                  <div class="form__text">{{ dayjs(meta.updatedTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
                </t-form-item>
              </t-col>
            </t-row>
          </t-space>
        </t-form>
      </template>
    </FormInfo>

    <t-loading text="加载中..." size="small" v-if="pageData.loading" />
    <t-tabs v-else v-model="pageData.activeTab">
      <t-tab-panel :value="1" label="供应商信息" :destroy-on-hide="true" :lazy="true">
        <SupplierInfo :id mode="view" />
      </t-tab-panel>
      <t-tab-panel :value="2" label="备注信息" :destroy-on-hide="true">
        <div class="form__container">
          <FormTable
            :buttons="pageData.remarkButtons"
            :tableData="pageData.remarkFormData"
            :columns="pageData.remarkColumns"
          >
            <template #rowOperations="{ row }">
              <div v-if="row.hasDeleted === 0" class="form-table__row_operations">
                <t-link variant="text" theme="primary" @click="handleEditForm(row, false)" v-if="!pageData.readOnly"
                  >修改</t-link
                >
                <t-link variant="text" theme="primary" @click="handleEditForm(row, true)">查看</t-link>
                <t-link variant="text" theme="danger" :disabled="pageData.readOnly" @click="handleDeleteForm(row)"
                  >删除</t-link
                >
              </div>
              <div v-else>
                <t-link theme="danger" variant="text" :disabled="pageData.readOnly" @click="handleUnDeleteForm(row)"
                  >撤销删除</t-link
                >
              </div>
            </template>
          </FormTable>
        </div>
      </t-tab-panel>
    </t-tabs>
  </t-drawer>

  <EditRemark
    v-if="pageData.showEditTableForm"
    :showDialog="pageData.showEditTableForm"
    :editFormData="pageData.editTableFormData"
    @onConfirm="handleFormConfirm"
    @onCancel="pageData.showEditTableForm = false"
    :mode="pageData.editTableFormMode"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { defineAsyncComponent, reactive, toRaw, watch } from "vue";
import { MessagePlugin, type TableProps } from "tdesign-vue-next";

// 工具函数
import { http } from "@/utils/fetch";
import dayjs from "dayjs";
import { v4 as uuidv4 } from "uuid";

// 常量
import { EDIT_FORM_SAVE_BUTTON } from "@/common/constants";

// 业务数据
import { useUserStore } from "@/stores/modules/user";

// 动态组件
const SupplierInfo = defineAsyncComponent(() => import("./SupplierInfo.vue"));
const EditRemark = defineAsyncComponent(() => import("./EditRemark.vue"));

const props = defineProps(["dialogVisible", "id", "mode", "meta"]);
const emits = defineEmits(["close"]);

// const formInstance = ref<FormInstanceFunctions | null>(null);

// const GET_FORM_PATH = "/customer/findOne"; // 查询接口
const GET_REMARK_PATH = "/provider/findRemarkByProviderId"; // 查询接口
// const CREATE_FORM_PATH = "/customer/create"; // 创建接口
const UPDATE_REMARK_PATH = "/provider/editProviderRemark"; // 更新接口
const UPDATE_STATUS_PATH = "/provider/setStatus";
const userStore = useUserStore();

const pageData = reactive({
  loading: true,
  readOnly: false,
  activeTab: 1,
  remarkButtons: [
    {
      name: "新建",
      icon: "add",
      disabled: props.mode === "view",
      click: () => {
        handleNewForm();
      }
    }
  ],
  remarkColumns: [
    {
      colKey: "providerRemark",
      title: "备注",

      ellipsis: {
        theme: "light",
        placement: "bottom"
      }
    },
    {
      colKey: "createdTime",
      title: "提交时间",
      width: 200,
      cell: (h, { row }) => {
        return dayjs(row.createdTime).format("YYYY-MM-DD");
      }
    },
    {
      colKey: "createdByName",
      title: "提交人",
      width: 200
    }
  ] as TableProps["columns"],
  remarkFormData: [] as Record<string, any>[],
  newStatus: 0,
  showEditTableForm: false,
  editTableFormMode: "new",
  editTableFormData: {},
  emptyTableFormData: {
    id: "",
    createdTime: new Date().toISOString(),
    createdBy: userStore.userData?.id,
    createdByName: userStore.userData?.realName,
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    updatedByName: "",
    hasDeleted: 0,
    providerId: props.id,
    providerRemark: ""
  }
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  // 传入状态信息
  if (props.meta.originStatus !== 0 && props.meta.originStatus !== 1) {
    pageData.newStatus = 0;
  } else {
    pageData.newStatus = props.meta.originStatus;
  }
  if (props.mode !== "new") {
    // } else if (props.mode === "edit" || props.mode === "view") {
    const remarkData = await http("POST", `${GET_REMARK_PATH}?providerId=${encodeURIComponent(id)}`);
    pageData.remarkFormData = remarkData.data.map((item: Record<string, any>) => {
      return {
        ...item,
        localUUID: uuidv4()
      };
    });

    pageData.loading = false;

    if (props.mode === "view") {
      pageData.readOnly = true;
    }
  } else {
    pageData.loading = false;
  }
};

const handleNewForm = () => {
  const emptyTableFormDataToRaw = toRaw(pageData.emptyTableFormData);
  const emptyTableFormData = structuredClone(emptyTableFormDataToRaw);
  pageData.showEditTableForm = true;
  pageData.editTableFormData = emptyTableFormData;
  pageData.editTableFormMode = "new";
};

const handleEditForm = (row: Record<string, any>, realOnly = false) => {
  if (realOnly) {
    pageData.editTableFormMode = "view";
  } else {
    pageData.editTableFormMode = "edit";
  }

  const tableFormDataToRaw = toRaw(row);
  const tableFormData = structuredClone(tableFormDataToRaw);

  pageData.editTableFormData = tableFormData;
  pageData.showEditTableForm = true;
};

const handleDeleteForm = (row: Record<string, any>) => {
  const index = pageData.remarkFormData.findIndex((item: Record<string, any>) => item.localUUID === row.localUUID);
  if (index > -1) {
    pageData.remarkFormData[index].hasDeleted = 1;
  }
};

const handleUnDeleteForm = (row: Record<string, any>) => {
  const index = pageData.remarkFormData.findIndex((item: Record<string, any>) => item.localUUID === row.localUUID);
  if (index > -1) {
    pageData.remarkFormData[index].hasDeleted = 0;
  }
};

const handleFormConfirm = (newData: Record<string, any>) => {
  // 先看原来的数组对象里面有没有这个数据，有就修改，没有就添加
  // 用localUUID来作为识别
  const index = pageData.remarkFormData.findIndex((item: Record<string, any>) => item.localUUID === newData.localUUID);
  if (index !== -1) {
    pageData.remarkFormData[index] = newData;
  } else {
    newData.localUUID = uuidv4();
    pageData.remarkFormData.push(newData);
  }
  pageData.showEditTableForm = false;
};

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  let remarkResultData;
  let statusResultData;

  if (props.mode === "view") {
    handleClose();
    return;
  }

  if (pageData.remarkFormData.length === 0) {
    MessagePlugin.error("请填写备注信息。");
    return;
  }

  // console.log(toRaw(pageData.formData));
  const postRemarkFormData = pageData.remarkFormData.filter(
    (item: Record<string, any>) => !(item.id === "" && item.hasDeleted === 1)
  );

  if (props.mode === "new") {
    // 新增
    MessagePlugin.error("不支持的操作。");
  } else {
    // 更新
    remarkResultData = await http("POST", UPDATE_REMARK_PATH, postRemarkFormData);

    if (props.meta.originStatus !== pageData.newStatus) {
      statusResultData = await http("POST", `${UPDATE_STATUS_PATH}?id=${props.id}&status=${pageData.newStatus}`);
    } else {
      statusResultData = { code: 200 };
    }
  }

  // 根据接口返回结果，提示操作成功或失败，并关闭对话框
  if (remarkResultData.code === 200 && statusResultData.code === 200) {
    emits("close", "success");
  }
};

const handleClose = () => {
  // 关闭对话框，并返回取消操作标识
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);

watch(
  () => pageData.newStatus,
  (newVal) => {
    if (newVal === 1) {
      MessagePlugin.warning("当前供应商状态被设置为禁用。");
    }
  }
);
</script>
